package com.abhimanyu.messaging;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import com.abhimanyu.messaging.model.IMessage;
import com.abhimanyu.messaging.model.TextMessage;

public class SendHubTextMessageSender implements IMessageSender {

	private static final String CONTACTS = "contacts";
	private static final String TEXT_MESSAGE = "text";
	private static final String SCHEDULED_AT = "scheduled_at";

	@SuppressWarnings("unchecked")
	public void sendMessage(IMessage message) {

		TextMessage textMessage = (TextMessage) message;
		JSONObject jsonMessage = new JSONObject();
		JSONArray jsonMessageArray = new JSONArray();
		jsonMessageArray.add(textMessage.getPhoneNumber());
		jsonMessage.put(CONTACTS, jsonMessageArray);
		jsonMessage.put(TEXT_MESSAGE, textMessage.getMessageText());
		String scheduledAt = textMessage.getScheduledAt();
		if (scheduledAt != null && !scheduledAt.isEmpty()) {
			jsonMessage.put(SCHEDULED_AT,
					createScheduleMessageString(scheduledAt));
		}
		try {
			sendPost(jsonMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// HTTP POST request
	private void sendPost(JSONObject message) throws Exception {

		String url = " https://api.sendhub.com/v1/messages/?username=7858069227&api_key=43cff8625bd348488d2bffac9ece1a81ac1fdacb";
		URL obj = new URL(url);
		//HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		// add request header
		con.setRequestMethod("POST");
		con.setReadTimeout(0);
		con.setRequestProperty("Content-Type", "application/json");
		// con.setRequestProperty("data", message.toJSONString());
		String urlParameters = message.toJSONString();

		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(urlParameters);
		// wr.writeBytes(message.toJSONString());
		wr.flush();
		wr.close();

		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'POST' request to URL : " + url);
		System.out.println("\nData : " + message.toJSONString());
		System.out.println("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// print result
		System.out.println(response.toString());
	}

	private String createScheduleMessageString(String timeOfDay) {
		DateFormat outputDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd'T'HH:mm:ssZ");
		DateFormat inputDateFormat = new SimpleDateFormat("hh:mma");
		String outputDate = null;
		try {
			Date scheduleDate = inputDateFormat.parse(timeOfDay);
			System.out.println(scheduleDate);
			Calendar inputCalendar = Calendar.getInstance();
			inputCalendar.setTime(scheduleDate);
			Calendar outputCalendar = Calendar.getInstance();
			outputCalendar.set(Calendar.HOUR_OF_DAY, inputCalendar.get(Calendar.HOUR_OF_DAY));
			outputCalendar.set(Calendar.MINUTE, inputCalendar.get(Calendar.MINUTE));
			outputDate = outputDateFormat.format(outputCalendar.getTime());
			System.out.println(outputDate);
		} catch (Exception e) {
			System.out.println(e);
		}

		return outputDate;
	}

	public static void main(String[] args) throws ParseException {
		new SendHubTextMessageSender().createScheduleMessageString("6:30pm");
		
		/*Date scheduledDate = inputDateFormat.parse(timeOfDay);
		outputDate = outputDateFormat.format(scheduledDate);
		Calendar currentTime = new GregorianCalendar();
		Calendar cal = new GregorianCalendar();
		cal.setTimeZone(TimeZone.getDefault());
		//cal.setTimeInMillis(scheduledDate.getTime());
		
		System.out.println(TimeZone.getDefault());
		
		System.out.println(outputDateFormat.format(cal.getTime()));
		System.out.println(outputDateFormat.format(currentTime.getTime()));
		cal.set(Calendar.DATE, currentTime.get(Calendar.DATE));
		cal.set(Calendar.MONTH, currentTime.get(Calendar.MONTH));
		cal.set(Calendar.YEAR, currentTime.get(Calendar.YEAR));
		cal.setTimeZone(currentTime.getTimeZone());
		outputDate = outputDateFormat.format(cal.getTime());
		System.out.println(cal.getTimeZone()); 
		System.out.println(currentTime.getTime()); 
		System.out.println(outputDate);*/
	}
}
